package com.peng.leetcode.dfs;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * MinPathSum
 *
 * @author: lupeng6
 * @create: 2021/1/20 21:45
 */
public class MinPathSum {

    public static void main(String[] args) {
        int[][] grid = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
        System.out.println(new MinPathSum().minPathSum(grid));
    }

    private int[][] operations = {{1, 0}, {0, 1}};

    private int rows;

    private int cols;

    private int[][] grid;

    private int[][] visited;

    private List<Integer> result = new ArrayList<>();

    public int minPathSum(int[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }
        this.grid = grid;
        this.rows = grid.length;
        this.cols = grid[0].length;
        this.visited = new int[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                visited[i][j] = -1;
            }
        }

        dfs(0, 0, grid[0][0]);
        Collections.sort(result);
        return result.get(0);
    }

    public void dfs(int x, int y, int sum) {
        if (x == rows - 1 && y == cols - 1) {
            result.add(sum);
            return;
        }
        visited[x][y] = sum;
        for (int[] operation : operations) {
            int newX = x + operation[0];
            int newY = y + operation[1];
            if (isArea(newX, newY)) {
                int newSum = sum + grid[newX][newY];
                if (visited[newX][newY] == -1 || visited[newX][newY] > newSum) {
                    dfs(newX, newY, newSum);
                }
            }
        }
    }

    public boolean isArea(int x, int y) {
        return x >= 0 && x < rows && y >= 0 && y < cols;
    }
}
